<?php
class Controller_Tests extends Controller_Base
{
	public function index()
	{
		$this->view->pageTitle = self::BASE_PAGE_TITLE.' --- Tests';
		$this->view->title = $this->view->pageTitle;
	}
	
	public function add()
	{
		$this->view->pageTitle = self::BASE_PAGE_TITLE.' --- Add Test';
		$this->view->title = $this->view->pageTitle;
	}
	
	public function save()
	{
		if(!$this->request->isPost()){
			return $this->_forward(array('act' => 'index'));
		}
		//need to write validation data
		$postData = 	$this->request->getPost();
		$model = new Model_DbTable_Tests();
		$id = $model->save($postData);
		if($id){
			return $this->redirect(array('act' => 'lists'));
		}
		return $this->_forward(array('act' => 'index'));
	}
	
	public function lists()
	{
		$this->view->pageTitle = self::BASE_PAGE_TITLE.' --- Tests List';
		$this->view->title = $this->view->pageTitle;
		
		$model = new Model_DbTable_Tests();
		$this->view->tests = $model->fetchAll();
	}
	
	public function update()
	{
		$id = (int)$this->request->getParam('id');
		if(!$id){
			return $this->_forward(array('act' => 'add'));
		}
		$model = new Model_DbTable_Tests();
		$this->view->test = $model->load($id);
		if(!$this->view->test){
			return $this->_forward(array('act' => 'add'));
		}
	}
	
	public function csv()
	{
		$this->disabledView = true;
		$model = new Model_DbTable_Tests();
		$tests = 	$model->fetchAll();
		$csvStr = 'id, name, subject'.PHP_EOL;
		foreach ($tests as $test){
			$csvStr .= $test->id.','.$test->name.','.$test->subject.PHP_EOL;
		}
		header("Content-type: text/csv");
		header("Content-Disposition: attachment; filename=tests.csv");
		header("Pragma: no-cache");
		header("Expires: 0");
		echo $csvStr;
	}
	
	public function delete()
	{
		$id = (int)$this->request->getParam('id');
		if(!$id){
			return $this->_forward(array('act' => 'lists'));
		}
		$model = new Model_DbTable_Tests();
		$model->delete(array('id' => $id));
		$this->_forward(array('act' => 'lists'));
	}
}